package com.manong.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.manong.domain.Department;
import com.manong.exception.BusinessExp;
import com.manong.mapper.DepartmentMapper;
import com.manong.query.QueryObject;
import com.manong.service.IDepartmentService;
import com.manong.util.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;

@Service
public class DepartmentServiceImpl implements IDepartmentService {

    private DepartmentMapper departmentMapper;

    @Autowired
    public void setDepartmentMapper(DepartmentMapper departmentMapper) {
        this.departmentMapper = departmentMapper;
    }

    @Override
    public void save(Department department) {
        departmentMapper.insert(department);
    }

    @Override
    public void delete(Long id) {
        if(id == null){
            throw new BusinessExp("参数不能为空");
        }
        int count = departmentMapper.deleteByPrimaryKey(id);
        // count 影响行数， 如果count == 0 表示删除失败
        if(count == 0){
            throw new BusinessExp("删除失败");
        }
    }

    @Override
    public void update(Department department) {
        departmentMapper.updateByPrimaryKey(department);
    }

    @Override
    public Department get(Long id) {
        if(id == null){
            throw new BusinessExp("id不能为空");
        }
        Department department = departmentMapper.selectByPrimaryKey(id);
        if(department == null){
            throw new BusinessExp("非法操作");
        }
        return department;
    }

    @Override
    public List<Department> getAll() {
        return departmentMapper.selectAll();
    }

    @Override
    public PageInfo query(QueryObject qo) {
        if(qo.getPageSize() == -1){
            List<Department> departments = departmentMapper.selectForList(qo);
            return new PageInfo(departments);
        }else {
            //PageHelper进行分页操作
            //告诉PageHelper 当前页是多少 每页显示数据
            PageHelper.startPage(qo.getPageNum(), qo.getPageSize());
            //调用分页方法
            List<Department> departments = departmentMapper.selectForList(qo);
            return new PageInfo(departments);
        }
    }

    @Override
    public void saveOrUpdate(Department department) {
        if(department == null){
            throw new RuntimeException("非法操作");
        }
        if(department.getId() == null){
            this.save(department);
        } else {
            this.update(department);
        }
    }
}
